package com.example.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import javax.annotation.Resource;

/**
 * Created by 文科 on 2015/11/21.
 */
@Configuration
@EnableCaching
public class CacheConfiguration extends CachingConfigurerSupport {

    Logger logger = LoggerFactory.getLogger(CacheConfiguration.class);

    //@Resource RedisTemplate redisTemplate;

    @Bean
    public KeyGenerator keyGenerator() {

        return (target,method,params) -> {

            StringBuilder builder = new StringBuilder(target.getClass().getName());
            builder.append(".");
            builder.append(method.getName());
            for(Object param:params){
                builder.append(param.toString());
            }

            String key = builder.toString();

            logger.info("build cache key:{}",key);

            return key;
        };

    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        logger.info("init cacheManager");
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){

        StringRedisTemplate redisTemplate = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
